<script setup lang="ts">
import CustomNavbar from '@/components/CustomNavbar.vue'
// import XtxSwiper from '@/components/XtxSwiper.vue'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { onLoad } from '@dcloudio/uni-app'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import { ref } from 'vue'
import CategoryPanel from './CategoryPanel.vue'
import HotPanel from './HotPanel.vue'
import type { XtxGuessInstance } from '@/types/components'
import PageSkeleton from './PageSkeleton.vue'

// 获取轮播图数据
const bannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  bannerList.value = res.result
}

// 获取前台分类数据
const categoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  categoryList.value = res.result
}

// 获取热门推荐数据
const hotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  hotList.value = res.result
}

// 获取猜你喜欢组件实例
const guessRef = ref<XtxGuessInstance>()
// 滚动触底事件
const onScrolltolower = () => {
  guessRef.value?.getMore()
}

// 下拉刷新
const isTriggered = ref(false) // 下拉刷新状态
const onRefresherrefresh = async () => {
  isTriggered.value = true // 开启动画
  guessRef.value?.resetData() // 重置猜你喜欢组件数据
  // 加载数据
  await Promise.all([
    getHomeBannerData(),
    getHomeCategoryData(),
    getHomeHotData(),
    guessRef.value?.getMore(),
  ])
  isTriggered.value = false // 关闭动画
}

// 骨架屏是否加载中标记
const isLoading = ref(false)

// 骨架屏+页面加载
onLoad(async () => {
  isLoading.value = true
  // getHomeBannerData()
  // getHomeCategoryData()
  // getHomeHotData()
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})
</script>

<template>
  <!--导航栏-->
  <CustomNavbar />
  <!-- 滚动容器 -->
  <scroll-view
    refresher-enabled
    @refresherrefresh="onRefresherrefresh"
    :refresher-triggered="isTriggered"
    @scrolltolower="onScrolltolower"
    scroll-y
  >
    <!--骨架屏-->
    <PageSkeleton v-if="isLoading" />
    <template v-else>
      <!--轮播图-->
      <XtxSwiper :list="bannerList" />
      <!--首页分类-->
      <CategoryPanel :list="categoryList" />
      <!--热门推荐-->
      <HotPanel :list="hotList" />
      <!--猜你喜欢-->
      <XtxGuess ref="guessRef" />
    </template>
  </scroll-view>
</template>

<style lang="scss">
/* #ifdef APP-PLUS */
#app,
/* #endif */
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
